package com.meihua.baoleyi.ui;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.meihua.baoleyi.R;
import com.meihua.baoleyi.base.BaseActivity;
import com.meihua.baoleyi.common.APIServer;
import com.meihua.baoleyi.common.MyApp;
import com.meihua.baoleyi.dialog.ReleasePhotoDialog;
import com.meihua.baoleyi.net.NetHelper;
import com.meihua.baoleyi.utils.FileUtil;
import com.meihua.baoleyi.utils.ToastUtil;
import com.meihua.baoleyi.view.CatLoadingView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.TreeMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * Created by liming on 2017/10/17
 * 手持身份证件
 */

public class CheckIdSubmitActivity extends BaseActivity {

    @Bind(R.id.iv_shouchi_picture)
    ImageView iv_shouchi_picture;
    @Bind(R.id.tv_sumbit)
    TextView tvSumbit;
    @Bind(R.id.text_title)
    TextView textView;

    public static final int PHTOT_REQUEST_SHOUCHI = 0x3;
    private String mShouchiPath = null;
    private static final int REQUEST_CAMERA_CODE = 0x9005;
    private static final int REQUEST_PHOTO_CODE = 0x9006;
    String authid;
    private String userName; //真实姓名
    private String userIdcard; //身份证号码
    private String imgReverse; //身份证背面照
    private String imgFront; //身份证正面照

    private int upCount = 0;
    private String[] upParamsList = new String[]{"", "", ""};
    private CatLoadingView dialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_id_check_submit);
        ButterKnife.bind(this);
        initView();
    }

    /**
     * 初始化数据
     */
    private void initView() {
        textView.setText("身份认证");
        userName = getIntent().getStringExtra("user_name");//用户名
        userIdcard = getIntent().getStringExtra("user_idcard");//身份证号码
        imgReverse = getIntent().getStringExtra("img_reverse");//正面照
        imgFront = getIntent().getStringExtra("img_front");//反面照
    }

    /**
     * 点击事件
     * @param v
     */
    @OnClick({R.id.text_back,R.id.iv_shouchi_picture,R.id.tv_sumbit})
    public void onViewClick(View v) {
        switch (v.getId()){
            case R.id.text_back: //返回
                finish();
                break;
            case R.id.iv_shouchi_picture: //手持身份证照
                goImageGridActivity(REQUEST_CAMERA_CODE,REQUEST_PHOTO_CODE);
                break;
            case R.id.tv_sumbit: //提交验证
                submit();
                break;
        }
    }

    /**
     * 点击提交验证
     */
    private void submit(){

        if(mShouchiPath == null){
            Toast.makeText(this,"请您选择手持身份证照片",Toast.LENGTH_SHORT).show();
            return;
        }

        //显示提示框
        if (dialog == null) {
            dialog = new CatLoadingView();
        }
        dialog.show(getSupportFragmentManager(), "loading");

        upCount = 0; //设置为默认的值
        for (int i = 0; i < 3; i++) {
            uploadCard(i);
        }
    }

    /**
     * 上传正面照
     * @param i
     */
    private void uploadCard(final int i) {

        String imgUrl = "";

        switch (i) {
            case 0: //正面照
                imgUrl = imgFront;
                    break;
            case 1: //背面照
                imgUrl = imgReverse;
                    break;
            case 2: //手持照
                imgUrl = mShouchiPath;
                    break;
        }

        //压缩图片后上传
        Luban.with(this)
                .load(new File(imgUrl))  // 传人要压缩的图片列表
                .ignoreBy(10)             // 忽略不压缩图片的大小
                .setTargetDir(Environment.getExternalStorageDirectory().getPath())   // 设置压缩后文件存储位置
                .setCompressListener(new OnCompressListener() { //设置回调
                    @Override
                    public void onStart() {}

                    @Override
                    public void onSuccess(final File file) {
                        OkGo.post(APIServer.PHOTO_UP)
                                .params("imgFile",file)//压缩文件
                                .execute(new StringCallback() {
                                    @Override
                                    public void onSuccess(String s, Call call, Response response) {
                                        try {
                                            JSONObject object = new JSONObject(s);
                                            if(object.getInt("code") == 200){
                                                //图片上传成功处理
                                                upCount++;
                                                switch (i) {
                                                    case 0: //正面照
                                                        upParamsList[0] = object.optString("msg");
                                                        break;
                                                    case 1: //背面照
                                                        upParamsList[1] = object.optString("msg");
                                                        break;
                                                    case 2: //手持照
                                                        upParamsList[2] = object.optString("msg");
                                                        break;
                                                }
                                                if (upCount == 3) {
                                                    submitData();
                                                }
                                            }else {
                                                ToastUtil.show(CheckIdSubmitActivity.this, object.getString("msg"));
                                                dialog.dismiss();
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                            dialog.dismiss();
                                        }

                                    }
                                });
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        Toast.makeText(CheckIdSubmitActivity.this, "提交失败", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    }
                }).launch();    //启动压缩

    }

    /**
     * 提交验证信息
     */
    private void submitData() {
        TreeMap<String, String> treeMap = new TreeMap<String, String>(){
            {
                put("user_id", MyApp.getInstance().getUser_id());//用户id
                put("user_name", userName);//用户名
                put("user_idcard", userIdcard);//身份证号码
                put("img_reverse", upParamsList[1]);//正面照
                put("img_front", upParamsList[0]);//反面照
                put("img_people", upParamsList[2]);//手持证件照
            }
        };
        NetHelper.post(APIServer.MY_AUTH, treeMap, false, new NetHelper.HttpCallBack() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                JSONObject object;
                try {
                    object = new JSONObject(s);
                    if ( object.optString("code").equals("200")) {
                        //请求成功
                        dialog.dismiss();
                        ToastUtil.show(CheckIdSubmitActivity.this, "认证提交成功,请等待");
                        Intent intent = new Intent();
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(CheckIdSubmitActivity.this, "服务器异常", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void goImageGridActivity(int cameraCode,int photoCode){
        ReleasePhotoDialog dialog = new ReleasePhotoDialog(CheckIdSubmitActivity.this,cameraCode,photoCode);
        dialog.show();
    }

    /**
     * 选取手持照片回调
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_CAMERA_CODE){
            mShouchiPath = FileUtil.getUtil().SDPATH + "photo_release" + MyApp.getInstance().time + ".png";
            checkEnable();
            if(mShouchiPath != null){
                Glide.with(this).load(mShouchiPath).into(iv_shouchi_picture);
            }

        }else if(requestCode == REQUEST_PHOTO_CODE) {
            if (data == null || data.getData() == null) {
                return;
            }
            String[] pojo = {MediaStore.MediaColumns.DATA};
            Cursor cursor = getContentResolver().query(data.getData(), pojo, null, null, null);
            int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
            cursor.moveToFirst();
            mShouchiPath = cursor.getString(columnIndex);
            checkEnable();
            if(mShouchiPath != null){
                Glide.with(this).load(mShouchiPath).into(iv_shouchi_picture);
            }
        }
    }

    /**
     * 点击状态设置
     */
    private void checkEnable() {
        if(!TextUtils.isEmpty(mShouchiPath)) {
            tvSumbit.setEnabled(true);
        }else {
            tvSumbit.setEnabled(false);
        }
    }
}
